package com.spring.shops.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.spring.shops.dao.TzProdMapper;
import com.spring.shops.dao.TzProdTagReferenceMapper;
import com.spring.shops.dao.TzSkuMapper;
import com.spring.shops.model.dto.SaveProductDTO;
import com.spring.shops.model.dto.SkuDTO;
import com.spring.shops.model.entity.TzProd;
import com.spring.shops.model.dto.ProdDTO;
import com.spring.shops.model.entity.TzProdTag;
import com.spring.shops.model.entity.TzProdTagReference;
import com.spring.shops.model.entity.TzSku;
import com.spring.shops.model.result.IPageIndexImg;
import com.spring.shops.model.result.ServerResponseEntityVoid;
import com.spring.shops.model.vo.ProductVO;
import com.spring.shops.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private TzProdMapper mapper;
    @Autowired
    private TzProdTagReferenceMapper referenceMapper;
    @Autowired
    private TzSkuMapper skuMapper;
    /**
     * 产品分页查询
     * @param dto
     * @return
     */
    @Override
    public ServerResponseEntityVoid<IPageIndexImg<ProductVO>> page(ProdDTO dto) {
        //获取当前页码
        Long currentPage = dto.getCurrent();
        //获取每页显示的条数
        Long size= dto.getSize();
        //设置分页初始值
        PageHelper.startPage(Math.toIntExact(currentPage), Math.toIntExact(size));
        //调用mapper层进行分页查询
        Page<TzProd> prodPage=mapper.page(dto);
        //创建IPageIndexImg对象
        IPageIndexImg<ProductVO> iPageIndexImg=new IPageIndexImg<>();
        iPageIndexImg.setSize(size);
        iPageIndexImg.setTotal(prodPage.getTotal());
        iPageIndexImg.setCurrent(currentPage);
        iPageIndexImg.setPages( prodPage.getTotal()/size+1);
        //获取所有记录
        List<TzProd> result = prodPage.getResult();
        List<ProductVO> data = new ArrayList<>();
        //属性拷贝
        for (TzProd tzProd : result) {
            ProductVO productVo = getProductVo(tzProd);
            //加入集合中
            data.add(productVo);
        }
        iPageIndexImg.setRecords(data);
        //返回结果集
        return ServerResponseEntityVoid.success(iPageIndexImg);
    }
    /**
     * 保存商品数据
     * @param dto
     * @return
     */
    //开启事务
    @Transactional
    @Override
    public boolean save(SaveProductDTO dto) {
        TzProd tzProd = getEntity(dto);
        //新增数据
        int rows=mapper.save(tzProd);
        //新增tagList
        List<Integer> tagList = dto.getTagList();
        //获取生成的产品id
        Long prodId = tzProd.getProdId();
        for (Integer tag : tagList) {
            Long tagId= Long.valueOf(tag);
            TzProdTagReference reference = new TzProdTagReference(1L, tagId, prodId, true, new Date());
            referenceMapper.save(reference);
        }
        //新增skuList
        List<SkuDTO> skuList = dto.getSkuList();
        for (SkuDTO dto2 : skuList) {
            Double oriPrice = dto2.getOriPrice();
            BigDecimal oriPrice2= BigDecimal.valueOf(oriPrice);
            Double price = dto2.getPrice();
            BigDecimal price2= BigDecimal.valueOf(price);
            TzSku tzSku = new TzSku(prodId, dto2.getProperties(),
                    oriPrice2, price2, dto2.getStocks(), dto2.getActualStocks(),
                    new Date(), new Date(), dto2.getPartyCode(),
                    dto2.getModelId(), dto2.getPic(), dto2.getSkuName(),
                    dto2.getProdName(), dto2.getVersion(), dto2.getWeight(),
                    dto2.getVolume(), dto2.getStatus(), (byte) 1);
            skuMapper.save(tzSku);
        }
        return true;
    }
    /**
     * 根据ids批量删除数据
     * @param integers
     * @return
     */
    @Transactional
    @Override
    public boolean deleteByProdIds(List<Long> integers) {
        for (Long prodId : integers) {
            //先根据prodId删除产品
            int rows1 = mapper.deleteByPrimaryKey(prodId);
            System.out.println(rows1);
            //然后删除产品-标签引用（根据prodId删除）
            int rows2 = referenceMapper.deleleByProdId(prodId);
            System.out.println(rows2);
            //最后逻辑删除产品属性表
            //先根据prodId查询出所有数据
            List<TzSku> list=skuMapper.selectByProdId(prodId);
            if(list!=null){
                for (TzSku tzSku : list) {
                    //设置它们每一个的isDelete字段为1
                    tzSku.setIsDelete((byte) 1);
                    //进行更新
                    skuMapper.updateByPrimaryKey(tzSku);
                }
            }

        }
        return true;
    }

    @Override
    public ServerResponseEntityVoid<ProductVO> getInfoById(Integer prodId) {
       //根据产品id获取信息
        TzProd prod=mapper.getById(prodId);
        ProductVO productVo = getProductVo(prod);
        //根据产品id获取所有的tag id 标签
        List<Integer> tagList=referenceMapper.selectByProdId(prodId);
        productVo.setTagList(tagList);
        //根据产品id获取所有的sku
        List<TzSku> skuList=skuMapper.selectByProdId(Long.valueOf(prodId));
        List<SkuDTO> skuListVO=new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //实体->dto
        for (TzSku sku : skuList) {
            skuListVO.add(new SkuDTO(
              sku.getSkuId(), sku.getProdId(), sku.getProperties(),sku.getOriPrice().doubleValue(),
                    sku.getPrice().doubleValue(),sku.getStocks(),sku.getActualStocks(),sdf.format(sku.getUpdateTime()),
                    sdf.format(sku.getRecTime()),sku.getPartyCode(),sku.getModelId(),sku.getPic(),sku.getSkuName(),
                    sku.getProdName(),sku.getVersion(), sku.getWeight(),sku.getVolume(),sku.getStatus(),sku.getIsDelete()
            ));
        }
        productVo.setSkuList(skuListVO);
        return ServerResponseEntityVoid.success(productVo);
    }
    /**
     * 更新数据
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public boolean updateInfo(SaveProductDTO dto) {
       //先更新产品信息
        TzProd entity = getEntity(dto);
        entity.setProdId(dto.getProdId());
        int rows = mapper.updateByPrimaryKey(entity);
        //然后更新标签信息（先删除再插入）
        //1.获取所有的标签信息
        List<Integer> tagList = dto.getTagList();
        int rows2 = referenceMapper.deleleByProdId(entity.getProdId());
        //插入所有的标签信息
        for (Integer tagId : tagList) {
            TzProdTagReference reference = new TzProdTagReference(
                    entity.getShopId(), Long.valueOf(tagId), entity.getProdId(), true,new Date()
            );
            referenceMapper.save(reference);
        }
        //插入所有的sku信息（先删除再插入）
        int rows3=skuMapper.deleteByProdId(entity.getProdId());
        System.out.println(rows3);
        //获取所有的sku信息
        List<SkuDTO> skuList = dto.getSkuList();
        for (SkuDTO dto1 : skuList) {
            TzSku tzSku = new TzSku(
              dto.getProdId(),dto1.getProperties(),BigDecimal.valueOf(dto1.getOriPrice()),
                    BigDecimal.valueOf(dto1.getPrice()),dto1.getStocks(),dto1.getActualStocks(),
                    new Date(),new Date(),dto1.getPartyCode(),dto1.getModelId(),dto1.getPic(),
                    dto1.getSkuName(),dto1.getProdName(),0,dto1.getWeight(),
                    dto1.getVolume(),dto1.getStatus(), (byte) 0);
            skuMapper.insert(tzSku);
        }

        return true;
    }

    //将传递进来的dto转换为实体对象
    public TzProd getEntity(SaveProductDTO dto){
        TzProd prod = new TzProd();
        Long shopId=1L;
        if(dto.getShopId()!=null){
            shopId=dto.getShopId();
        }
        prod.setShopId(shopId);
        prod.setProdName(dto.getProdName());
        prod.setOriPrice(BigDecimal.valueOf(dto.getOriPrice()));
        prod.setPrice(BigDecimal.valueOf(dto.getPrice()));
        prod.setBrief(dto.getBrief());
        prod.setPic(dto.getPic());
        prod.setImgs(dto.getImgs());
        prod.setStatus(dto.getStatus());
        prod.setCategoryId(dto.getCategoryId());
        prod.setTotalStocks(dto.getTotalStocks());
        Gson gson = new Gson();
        String json = gson.toJson(dto.getDeliveryModeVo());
        prod.setDeliveryMode(json);
        prod.setContent(dto.getContent());
        if(dto.getDeliveryTemplateId()!=null){
            prod.setDeliveryTemplateId(Long.valueOf(dto.getDeliveryTemplateId()));
        }
        prod.setUpdateTime(new Date());
        prod.setCreateTime(new Date());
        prod.setPutawayTime(new Date());
        return prod;
    }

    //根据实体类型获取VO类型
    public ProductVO getProductVo(TzProd tzProd){
        int prodId = tzProd.getProdId().intValue();
        int shopId = tzProd.getShopId().intValue();
        double oriPrice = tzProd.getOriPrice().doubleValue();
        double price = tzProd.getPrice().doubleValue();
        int categoryId = tzProd.getCategoryId().intValue();
        Integer deliveryTemplateId = null;
        if(tzProd.getDeliveryTemplateId()!=null){
            deliveryTemplateId= tzProd.getDeliveryTemplateId().intValue();
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 使用format方法将Date对象转换为String对象
        String updateTime = dateFormat.format(tzProd.getUpdateTime());
        String createTime = dateFormat.format(tzProd.getCreateTime());
        String putawayTime = dateFormat.format(tzProd.getPutawayTime());
        return new ProductVO(prodId,shopId, tzProd.getProdName(),oriPrice,
                price, tzProd.getBrief(),tzProd.getPic(), tzProd.getImgs(),
                tzProd.getStatus(), categoryId, tzProd.getSoldNum(), tzProd.getTotalStocks(),
                tzProd.getDeliveryMode(), tzProd.getContent(), deliveryTemplateId,
                updateTime,createTime,putawayTime, tzProd.getVersion(),null,null,null);
    }
}
